import base64
import hashlib
import os
import time
import uuid
from datetime import datetime, timedelta

from django.core.cache import cache
from django.core.paginator import Paginator
from django.db.models import Sum

from django.core import serializers
from django.http import HttpResponse
from django.utils import timezone
from rest_framework.generics import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response

from Tool_module.serializers import UserSerializer, xiangmuSerializer, xiangmu_chanyuSerializer, daSerializer
from Tool_module.tool_api import get_login_info, Myjwt_token, OrderStatus
from cs_weixinapp import models

from cs_weixinapp.models import xiangmu_user, xiangmu, xiangmu_chanyu
from djangoProject import settings
from djangoProject.settings import BASE_DIR


class appInfo(APIView):
    def get(self, request):
        id = request.GET.get("id")
        user = xiangmu_user.objects.filter(id=id).first()
        print(user.admin, user.is_on_sale, '打印的user数555555555555555555555555555据查询')
        if user.admin is not None:
            xiangmu_cid = xiangmu_user.objects.filter(user_admin=user.admin).get()
            cid = xiangmu_cid.id
            fabuxiangmu = xiangmu.objects.filter(cid=cid).all()
            print(fabuxiangmu.all(), '打印的category数据查询5')
            category_list_serializer = xiangmuSerializer(fabuxiangmu, many=True)
            print(category_list_serializer.data, '打印的category_list_serializer数据查询')
            return Response({
                "errno": 0,
                "errmsg": "",
                "admin": 1,
                "data": category_list_serializer.data})
        else:
            print("未查找到管理员！7777777777777777777777777")
            return Response({  # 团队不存在
                "errno": 500,
                "errmsg": "团队不存在",
                "data": 0,
            })


class ShowSettingsDetailView(APIView):
    def get(self, request, *args, **kwargs):
        return Response({
            "errno": 0,
            "errmsg": "",
            "data": {'id': 1, 'banner': 1, 'channel': 1, 'index_banner_img': 0, 'notice': 1}
        })


class LoginByWeixin(APIView):
    cache.set('token', 'header.payload.signature', 10)
    # 取出token
    token = cache.get('token')

    def post(self, request, ):

        current_time = datetime.now()

        # 获取当前时间的时间戳（秒为单位），并转换为毫秒
        regist_datatime = int(current_time.timestamp() * 1)
        # print(regist_datatime)

        param = request.data
        if not param.get('code'):
            return Response({
                "errno": 1000,
                "errmsg": "登录失败，openid无效"
            })
        else:
            code = param.get('code')
            user_data = get_login_info(code)  # 通过微信接口获取sessionkey
            user = xiangmu_user.objects.filter(weixin_openid=user_data['openid']).first()
            print(user, '--------------------------------------------------')
            if user:
                # 序列化用户对象
                serializer = UserSerializer(user).data

                user_data['user_id'] = serializer.get('id')
                key = Myjwt_token(user_data)  # 获取加密的token
                key = key.jiami()
                # 进行保存用户登录信息
                if user_data:
                    users = xiangmu_user.objects.get(id=serializer.get('id'))

                    # serializer['user_img_url'] = 'http://192.168.101.4:8000//images/'+serializer.get('user_img_url')
                    print(serializer, )

                    # 更新用户的last_login_time和last_login_ip
                    now_time = datetime.now()
                    users.xiangmu_time = now_time.strftime("%Y-%m-%d %H:%M:%S")
                    print(datetime.now(), '更新用户的last_login_time和last_login_ip')

                    return Response({"errno": 0,
                                     "errmsg": "",
                                     'data': {
                                         'token': key,
                                         'userInfo': serializer,
                                         'is_new': 0,
                                     }})

            else:
                username = '微信用户' + str(uuid.uuid4())[:6]  # 随机生成用户名
                # print("未保存此用户")
                # 创建一个新的User实例
                new_user = xiangmu_user.objects.create(
                    beiyong=code,  # 假设openid在session中

                    weixin_openid=user_data['openid'],
                    user_name=username,
                    user_img_url='http://192.168.101.4:8000//images/falsmncAZxXr302444d8f6ce90118ec449a56dc8b59a.jpg',

                )

                # 保存用户到数据库
                new_user.save()
                serializer = UserSerializer(user).data
                user_data['user_id'] = serializer.get('id')
                key = Myjwt_token(user_data)  # 获取加密的token
                key = key.jiami()  # 获取加密的token

                return Response(
                    {"errno": 0,
                     "errmsg": "",
                     'data':
                         {
                             'token': key,
                             'userInfo': serializer,
                             'is_new': 0,
                         }})
class Show_admin(APIView):
    def get(self, request, ):
        mobile = request.GET.get("mobile")
        admin = request.GET.get("admin")
        user = xiangmu_user.objects.filter(user_mobile=mobile).first()
        if user.user_admin is not None:
            return Response({
                "errno": 301,
                "errmsg": "当前用户已是管理员："+user.user_admin
            })
        user.is_on_sale = 1
        user.user_admin = admin
        user.save()
        print(user.admin, user.is_on_sale, '打印的user数5555555555据查询')
        return Response({
            "errno": 0,
            "errmsg": "设置成功！！",
        })

    def post(self, request, ):
        print(request.data.get('userInfo'), '打印的request.data数据查询')
        is_on_root=0
        userInfo = request.data.get('userInfo')
        user_id = userInfo.get('id')
        user = xiangmu_user.objects.filter(id=user_id).first()

        print(user.user_root, user.is_on_sale, '打印的user数5555555555据查询')
        if user.user_root is not None and user.is_on_root == 1:
            if userInfo.get('user_root') == user.user_root:
                is_on_root = 1
        else:
            is_on_root = 0
        print(is_on_root, '打印的is_on_root数据查询')
        user= UserSerializer(user).data
        print(user, '打印的user数据查询')
        return Response({
            "errno": 0,
            "errmsg": "",
            'is_on_admin': is_on_root,
            'data': UserSerializer(user).data
        })
        # id = request.GET.get("id")
        # user = xiangmu_user.objects.filter(id=id).first()
        # print(user.admin, user.is_on_sale, '打印的user数5555555555据查询')


class deailindex(APIView):
    def post(self, request, ):
        id = request.data.get("xiangmu_id")
        user_id = int(request.data.get("user_id"))
        print(user_id, '打印的id数据查询', type(user_id), datetime.now())
        # 所有参与查询
        is_on_admin = xiangmu.objects.filter(id=id).first()
        print(is_on_admin.cid_id, '打印的is_on_admin数据查询', type(is_on_admin.cid_id))

        if user_id == is_on_admin.cid_id:
            is_on_admin = 1
        else:
            is_on_admin = 0
        xiangmus = xiangmu_chanyu.objects.filter(sid_id=id).values_list('cid_id', flat=True).distinct()
        xiangmu_list = []
        for i in xiangmus:
            print(i, '打印的参与的项目数据查询')
            xiangmuuserlist = xiangmu_user.objects.filter(id=i).values('user_name', 'user_img_url', 'id')

            category_list_serializer = daSerializer(xiangmuuserlist, many=True)  # 所有参与的项目
            for user_data in category_list_serializer.data:
                xiangmu_list.append(user_data)
        print(xiangmu_list, '打印的参与的项目数据查询liebiao')

        return Response({
            "errno": 0,
            "errmsg": "",
            'is_on_admin': is_on_admin,
            "data": xiangmu_list})


class settingssave(APIView):
    def post(self, request):
        print(request.data, "打印的request.data数据查询")
        if request.data.get("mobile") == "":
            return Response({
                "errno": 500,
                "errmsg": "手机号不能为空!!!"
            })
        dailiname = request.data.get("name")
        daili_id = xiangmu_user.objects.filter(user_admin=dailiname).first()
        if not daili_id:
            return Response({
                "errno": 500,
                "errmsg": "该代理不存在!!请核实代理邀请码!"
            })
        if request.data.get('nickName') == '':
            return Response({
                "errno": 500,
                "errmsg": "名字不能为空或特殊符号！！!"
            })
        mobile = request.data.get("mobile")
        name = request.data.get('nickName')
        avatar = request.data.get('avatar')
        weixinid = request.data.get('weixinid')
        print(type(weixinid), weixinid, "打印的weixinid数据查询")

        user = xiangmu_user.objects.get(weixin_openid=weixinid)
        print(type(user.weixin_openid), "打印的user数据查询")
        user.admin = dailiname
        user.user_name = name
        user.user_mobile = mobile
        user.user_img_url = 'http://192.168.101.4:8000//images/' + avatar

        user.save()

        return Response({
            "errno": 0,  # 成功
            "errmsg": "",
            "data": {
            }
        })


class settingsdata(APIView):
    def get(self, request):
        print(request.data, "===================================================Cart_index")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {

                }
            }
        )


class uploadchanyuimg(APIView):

    def post(self, request):
        print(request.FILES, "======666666666666666666666img")
        myfile = request.FILES['image']

        filename = os.path.basename(myfile.name)
        file_path = os.path.join('static/path_to_save_file', filename)
        with open(file_path, 'wb+') as destination:
            print(destination, "==========upload999999999999chanyuimg")
            for chunk in myfile.chunks():
                destination.write(chunk)
        return HttpResponse(filename)


class uploaduserimg(APIView):
    def post(self, request):
        myfile = request.FILES['userimg']
        filename = os.path.basename(myfile.name)
        file_path = os.path.join('static', 'user_img', filename)

        # 确保目录存在
        os.makedirs(os.path.dirname(file_path), exist_ok=True)

        with open(file_path, 'wb+') as destination:
            for chunk in myfile.chunks():
                destination.write(chunk)

        return HttpResponse(filename)


def serve_image(request, image_name):
    ifile_path = os.path.join('static', 'user_img', image_name)
    print(ifile_path, '打印的ifile_path数据查询')

    if not os.path.exists(ifile_path):
        ifile_path = os.path.join('static', 'path_to_save_file', image_name)
        if not os.path.exists(ifile_path):
            return HttpResponse("Image not found", status=404)

    # 打开图片文件并读取内容
    with open(ifile_path, 'rb') as image_file:
        response = HttpResponse(image_file.read(), content_type="image/jpeg")
        return response


class savercomment(APIView):

    def post(self, request):

        mobile = request.data.get('mobile')
        text = request.data.get('text')
        code = request.data.get('code')
        img_url = request.data.get('img_url')
        xiangmuname = request.data.get('xiangmuname')

        if mobile == "":
            return Response(
                {
                    "errno": 301,
                    "errmsg": "请输入手机号!!!",
                }
            )
        if request.data.get('user'):
            user = xiangmu_user.objects.filter(id=request.data.get('user').get('id')).first()
            print(request.data.get('user'), '打印的request,data,user数据查询')
            cart = xiangmu_chanyu.objects.create(xiangmu_name=xiangmuname,
                                                 xiangmu_canyuimg=img_url,
                                                 user_mobile=mobile,
                                                 xiangmu_tuandui=code,
                                                 xiangmu_daili=text,
                                                 cid_id=request.data.get('user').get('id'),
                                                 sid_id=request.data.get('xiangmuid')

                                                 )
            cart.save()
            return Response(
                {
                    "errno": 0,
                    "errmsg": "参与成功！",
                }
            )
        else:
            user_data = get_login_info(code)  # 通过微信接口获取sessionkey
            print(user_data, '打印的user_data数据查询')
            user = xiangmu_user.objects.filter(weixin_openid=user_data['openid']).first()
            serializer = UserSerializer(user).data
            print(serializer.get('id'), '5555555555555555555555555', type(serializer))

            cart = xiangmu_chanyu.objects.create(xiangmu_name=xiangmuname,
                                                 xiangmu_canyuimg=img_url,
                                                 user_mobile=mobile,
                                                 xiangmu_tuandui=code,
                                                 xiangmu_daili=text,
                                                 cid_id=serializer.ge('id'),
                                                 sid_id=request.data.get('xiangmuid'),
                                                 )
            cart.save()
            return Response(
                {
                    "errno": 0,
                    "errmsg": "参与成功！",
                }
            )


class Tuandui(APIView):
    def get(self, request):
        id = request.GET.get("id")
        print(id, "打印的id团队自己发布的项目数据查询")
        user = xiangmu_user.objects.filter(id=id).first()
        print(user.user_admin, user.is_on_sale, '打印的user数555555555555555555555555555据查询')
        if user.user_admin and user.is_on_sale == 1:
            fabuxiangmu = xiangmu.objects.filter(cid=id).all()
            print(fabuxiangmu.all(), '打印的category数据查询')
            category_list_serializer = xiangmuSerializer(fabuxiangmu, many=True)
            print(category_list_serializer.data, '打印的category_list_serializer数据查询')
            return Response({
                "errno": 0,
                "errmsg": "",
                "admin": 1,
                "data": category_list_serializer.data})
        else:
            return Response({  # 团队不存在
                "errno": 500,
                "errmsg": "团队不存在",
                "data": 0,
            })

    def post(self, request):
        print(request.data, "===================================================CartUpdate")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


#
#
class Newxiangmu(APIView):
    def post(self, request):
        print(request.data, "===================================================Newxiangmu")
        datatime = datetime.now()
        times = int(request.data.get('times'))

        new_datetime = datatime + timedelta(hours=times)

        formatted_datetime = new_datetime.strftime("%Y-%m-%d %H:%M:%S")
        print(formatted_datetime)

        xiangmusaver = xiangmu.objects.create(
            xiangmu_name=request.data.get('name'),
            xiangmu_jieshao=request.data.get('xiangmujieshao'),
            xiangmu_yaoqiu=request.data.get('xiangmuyaoqiu'),
            is_on_modibo=request.data.get('mobile'),
            is_on_text=request.data.get('shoujitext'),
            is_on_img=request.data.get('shoujiimg'),
            cid_id=request.data.get('id'),
            xiangmu_time=formatted_datetime
        )
        xiangmusaver.save()
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class CommonIndex(APIView):
    def post(self, request):
        print(request.data, "===================================================CartCheckedView")
        xiangmu_list = xiangmu.objects.filter(id=request.data.get('id')).all()

        print(xiangmu_list, '打印的category数据查询')
        category_list_serializer = xiangmuSerializer(xiangmu_list, many=True)

        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": category_list_serializer.data
            }
        )


#
#
class deletexiangmu(APIView):
    def post(self, request):
        print(request.data, "===================================================deletexiangmu")
        xiangmu_list = xiangmu.objects.filter(id=request.data.get('id')).delete()
        return Response(
            {
                "errno": 0,
                "errmsg": "删除成功！",
            }
        )


class GoodsCountView(APIView):
    def get(self, request):
        print(request.data, "===================================================GoodsCountView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class GoodsListView(APIView):
    def get(self, request):
        print(request.data, "===================================================GoodsListView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class GoodsShareView(APIView):
    def get(self, request):
        print(request.data, "===================================================GoodsShareView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class SaveUserIdView(APIView):
    def get(self, request):
        print(request.data, "===================================================购物车")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class AddressDetailView(APIView):
    def get(self, request):
        print(request.data, "===================================================购物车")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class DeleteAddressView(APIView):
    def get(self, request):
        print(request.data, "===================================================购物车")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class SaveAddressView(APIView):
    def get(self, request):
        print(request.data, "===================================================购物车")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class GetAddressesView(APIView):
    def get(self, request):
        print(request.data, "===================================================购物车")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class RegionListView(APIView):
    def get(self, request):
        print(request.data, "===================================================购物车")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class PayPrepayIdView(APIView):
    def get(self, request):
        print(request.data, "===================================================购物车")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class OrderSubmitView(APIView):
    def get(self, request):
        print(request.data, "===================================================购物车")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class OrderDeleteView(APIView):
    def get(self, request):
        print(request.data, "===================================================OrderDeleteView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class OrderCancelView(APIView):
    def get(self, request):
        print(request.data, "===================================================OrderCancelView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class OrderConfirmView(APIView):
    def get(self, request):
        print(request.data, "===================================================OrderConfirmView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class OrderCountView(APIView):
    def get(self, request):
        print(request.data, "===================================================OrderCountView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class OrderExpressInfoView(APIView):
    def get(self, request):
        print(request.data, "===================================================OrderExpressInfoView")

        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class OrderGoodsView(APIView):
    def get(self, request):
        print(request.data, "===================================================OrderGoodsView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class OrderExpressView(APIView):
    def get(self, request):
        print(request.data, "===================================================OrderExpressView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class FootprintListView(APIView):
    def get(self, request):
        print(request.data, "===================================================FootprintListView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class FootprintDeleteView(APIView):
    def get(self, request):
        print(request.data, "===================================================FootprintDeleteView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class SearchIndexView(APIView):
    def get(self, request):
        print(request.data, "===================================================SearchIndexView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class SearchHelperView(APIView):
    def get(self, request):
        print(request.data, "===================================================SearchHelperView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class SearchClearHistoryView(APIView):
    def get(self, request):
        print(request.data, "===================================================SearchClearHistoryView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )


class ShowSettingsView(APIView):
    def get(self, request):
        print(request.data, "===================================================ShowSettingsView")
        return Response(
            {
                "errno": 0,
                "errmsg": "",
                "data": {
                    "cartTotal": {
                        "goodsCount": 0
                    }
                }
            }
        )
